package com.lap.generator.domain.template.strategy;

import java.io.IOException;
import java.util.List;
import com.lap.generator.application.assembler.ModelTransformer;
import com.lap.generator.commons.exception.GeneratorException;
import com.lap.generator.commons.tools.FileUtil;
import com.lap.generator.commons.tools.PackageUtil;
import com.lap.generator.domain.CoreFile;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.template.CodeGenContext;
import com.lap.generator.domain.template.CodeTemplate;
import com.lap.generator.domain.valueobject.CodeType;
import com.lap.generator.infrastructure.persistence.TemplateEngine;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PersistencePoGen implements CodeTemplate<CoreFile> {
  @Override
  public CodeType getType() {
    return CodeType.DRIVING;
  }

  @Override
  public List<CoreFile> generate(CodeGenContext context) {
    TemplateModel model = ModelTransformer.transform(context.tableMeta(), context.envConfig());
    try {
      TemplateEngine engine = new TemplateEngine();

      String poContent = engine.processTemplate("adapter/driving/PersistencePo.java.ftl", model);
      String poName = FileUtil.resolverFile("java", model.getClassName(), "Po");
      String poPackName = PackageUtil.pack2Path(model.getBasePackage(), "adapter.driving.persistence",
          model.getModule(), "po");
      CoreFile poFile = 
          CoreFile.builder()
          .path(poPackName)
          .fileName(poName)
          .content(poContent)
          .build();

      String converterContent =
          engine.processTemplate("adapter/driving/PersistenceConverter.java.ftl", model);
      String converterName = FileUtil.resolverFile("java", model.getClassName(), "Converter");
      String convertPackName = PackageUtil.pack2Path(model.getBasePackage(),
          "adapter.driving.persistence", model.getModule());
      CoreFile convertFile =
          CoreFile.builder()
          .path(convertPackName)
          .fileName(converterName)
          .content(converterContent)
          .build();

      return List.of(poFile, convertFile);
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("Po engine error:", e);
    }
  }
}
